import React, { Component } from 'react';
import {
  StyleSheet, View, Image, Dimensions, ScrollView, DeviceEventEmitter, TouchableOpacity, Alert,
} from 'react-native';
import {
  Text, Tab, Tabs, Icon, ActionSheet,
} from 'native-base';

import ZlstIcon from '../../../components/zlst-icons';
import Theme from '../../../native-base-theme/variables/commonColor';
import * as devicesRequest from '../../../services/devicesRequest';
import { produce } from 'immer';
import ImagePicker from 'react-native-image-crop-picker';
import { UtilToast } from '../../../utils/util-method';
import * as todoService from '../../../services/todo';

import Tab1 from './devicesDetailBaseInfo';
import Tab2 from './assetInformation';
import Tab3 from './maintenanceRecord';
import TabDoc from './assetDoc';

class devicesInfo extends Component {
  equipmentId = '';

  equipmentCode = '';

  swipeToDetailListhener = null;

  static navigationOptions = {
    header: null,
  }


  // 构造方法
  constructor(props) {
    super(props);
    this.state = {
      showLoading: true,
      listData: {},
      propertyData: {},
      fromNavigation: false,
      sysParams: [],
    };
  }

  // 初始化
  componentDidMount() {
    if (this.props.navigation) { // 路由带入参数
      // console.log('===', this.props.navigation.state.params.code);
      const par = this.props.navigation.state.params;
      if (par.code) {
        this.equipmentCode = par.code;
        this.queryProperty(this.equipmentCode);
        this.codeQueryDevice(this.props.navigation.state.params);
      } else {
        this.equipmentCode = par.equipmentCode;
        this.queryProperty(this.equipmentCode);
        this.queryDeviceInfo(this.props.navigation.state.params);
      }
    } else {
      this.swipeToDetailListhener = DeviceEventEmitter.addListener('swipeToDetail', this.queryDeviceInfoEvent);
    }
    this.querySysParams();
  }

  componentWillUnmount() {
    // DeviceEventEmitter.removeAllListeners('swipeToDetail', this.queryDeviceInfo);
    if (this.swipeToDetailListhener) {
      this.swipeToDetailListhener.remove();
    }
  }

  // 查询设备资产信息
  queryProperty = async (params) => {
    if (!params) {
      return;
    }
    let code = '';
    // 路由带入参数this.props.navigation
    if (this.props.navigation) {
      code = params;
    } else {
      code = params.equipmentCode;
    }
    // const { code, fromNavigation } = params;
    const ajaxData = {
      equipmentCode: code,
    };
    try {
      const list = await devicesRequest.getFindEquipmentAssetByCode(ajaxData);
      this.setState(produce(draft => {
        draft.propertyData = list.data;
      }));
      this.queryProperty();
      // console.log('===========', this.state.propertyData);
    } catch (error) {
      this.setState({ showLoading: false });
    }
  }

  // 通过扫描二维码code查询详情数据
  codeQueryDevice = async (params) => {
    if (!params) {
      return;
    }
    DeviceEventEmitter.emit('showLoading', true);
    const { code, fromNavigation } = params;
    // const ajaxData = {
    //   equipmentCode: code,
    // };
    try {
      const list = await devicesRequest.getqueryEquipmentByEquipmentCode(code);
      if (list.data.serviceDate) {
        list.data.serviceDate = list.data.serviceDate.substring(0, 10);
      }

      if (list.data.installDate) {
        list.data.installDate = list.data.installDate.substring(0, 10);
      }

      if (list.data.productionDate) {
        list.data.productionDate = list.data.productionDate.substring(0, 10);
      }

      // list.data.serviceDate && list.data.serviceDate = list.data.serviceDate.substring(0, 10);
      // list.data.installDate && list.data.installDate = list.data.installDate.substring(0, 10);
      this.setState(produce(draft => {
        if (list.data !== null) {
          draft.listData = list.data;
        }
        draft.showLoading = false;
        DeviceEventEmitter.emit('showLoading', false);
      }));
    } catch (error) {
      this.setState({ showLoading: false });
      DeviceEventEmitter.emit('showLoading', false);
    }
  }

  queryDeviceInfoEvent = (params) => {
    this.setState({
      defaultPageIndex: 0,
    });
    this.queryProperty(params);
    this.queryDeviceInfo(params);
  }

  // 查询设备信息
  queryDeviceInfo = async (params) => {
    if (!params) {
      return;
    }
    DeviceEventEmitter.emit('showLoading', true);
    const { id, objType, equipmentCode, fromNavigation } = params;
    this.equipmentId = id;
    this.equipmentCode = equipmentCode;
    // console.log('======66666', this.equipmentId );
    // const ajaxData = {
    //   equipmentId: this.equipmentId,
    //   objType: objType,
    // };
    // console.log('请求参数', ajaxData);
    try {
      const list = await devicesRequest.getqueryEquipmentByEquipmentCode(equipmentCode);
      if (list.data.serviceDate) {
        list.data.serviceDate = list.data.serviceDate.substring(0, 10);
      }

      if (list.data.installDate) {
        list.data.installDate = list.data.installDate.substring(0, 10);
      }

      if (list.data.productionDate) {
        list.data.productionDate = list.data.productionDate.substring(0, 10);
      }

      this.setState(produce(draft => {
        draft.listData = list.data;
        draft.showLoading = false;
        DeviceEventEmitter.emit('showLoading', false);
      }));
    } catch (error) {
      this.setState({ showLoading: false });
      DeviceEventEmitter.emit('showLoading', false);
    }
  };

  // 查询系统参数
  querySysParams = async () => {
    try {
      const list = await devicesRequest.getQuerySysParams();
      this.setState(produce(draft => {
        draft.sysParams = list.data;
      }));
    } catch (error) {
      console.error(error);
    }
  };

  // 调用子组件（检维修历史页面）数据查询接口;
  _onChangeTab = (item) => {
    // console.log('==9999999999', this.equipmentId);
    switch (item.i) {
      case 2:
        this.refs.ref1.QueryMaintenanceHistory(this.equipmentCode);
        break;

      default:
        break;
    }
  };

  // 点击返回按钮
  _toMianPage = () => {
    if (this.props.navigation) {
      this.props.navigation.goBack();
    } else {
      DeviceEventEmitter.emit('swiperIncidentPageEvent', -1);
    }
  }

  // 显示图片
  _showDetaiImage = () => {

    if (this.state.listData.equipmentImage) {
      return {
        uri: `${devicesRequest.getDownloadImg}/${this.state.listData.equipmentImage}?token=${global.__TOKEN_ACCESS__}`,
      };
    }
    return require('../../../../assets/images/no-pic.png');
  }

  // 图片上传
  submitImg = async (images) => {
    DeviceEventEmitter.emit('showLoading', true);
    try {
      const imgResult = await todoService.uploadPic(images);
      if (imgResult.success === true) {
        this.updateImage(imgResult.data);
      }
      // console.log('URL', imgResult);
    } catch (error) {
      DeviceEventEmitter.emit('showLoading', false);
      UtilToast('图片上传失败，请检查网络！', 'danger');
    }
  }

  // 修改设备图片
  updateImage = async (imgResult) => {
    const ajaxData = {
      equipmentId: this.state.listData.equipmentId,
      equipmentImage: imgResult.fileId,
    };
    try {
      const list = await devicesRequest.getUpdateEquipmentImage(ajaxData);
      DeviceEventEmitter.emit('showLoading', false);
      this.setState(produce(draft => {
        if (list.resultCode === 0) {
          draft.listData.equipmentImage = list.data.equipmentImage;
        }
      }));
      UtilToast('上传图片成功！', 'success');
      DeviceEventEmitter.emit('refreshPageEvent'); // 刷新首页列表
      // console.log('===', list);
    } catch (error) {
      DeviceEventEmitter.emit('showLoading', false);
      UtilToast('网络异常，请检查网络！', 'danger');
    }
  }

  // 点击添加
  addBtn = () => {
    const { listData, sysParams } = this.state;
    const rolesAry = global.roles;
    const BUTTONS = ['故障申报', '取消'];
    // const BUTTONS = ['采集设备图片', '故障申报', '取消'];
    const CANCEL_INDEX = 3;
    // console.log('====', rolesAry, sysParams);
    // 采集设备图片按钮权限控制
    for (let i = 0; i < rolesAry.length; i++) {
      if (sysParams[0].paraValue === rolesAry[i].roleId) {
        BUTTONS.unshift('采集设备图片（从相册选择）');
        BUTTONS.unshift('采集设备图片（拍照）');
      }
    }
    return (
      /**
       * title 标题
       * options 里面的数组的内容，最好是字符串
       * cancelButtonIndex 取消按钮的索引，在options
       * destructiveButtonIndex 删除按钮的索引，在options ， 加红色的按钮
       * onPress 当点击选项的时候调用，同时传递给我们被点击的索引
       * tintColor 选项的颜色
       */
      ActionSheet.show(
        {
          options: BUTTONS,
          cancelButtonIndex: CANCEL_INDEX,
          // destructiveButtonIndex: DESTRUCTIVE_INDEX,
          // title: 'Testing ActionSheet',
        },
        buttonIndex => {
          console.log('===', BUTTONS[buttonIndex]);
          if (BUTTONS[buttonIndex] === '采集设备图片（拍照）') {
            ImagePicker.openCamera({
              width: 300,
              height: 400,
              cropping: false,
              compressImageQuality: 0.2,
            }).then(image => {
              Alert.alert(
                '提示',
                '是否上传图片',
                [
                  {
                    text: '取消',
                    style: 'cancel',
                  },
                  {
                    text: '确定',
                    onPress: () => {
                      const images = [{ uri: image.path, type: 'multipart/form-data', name: `${new Date().getTime()}.png` }];
                      this.submitImg(images);
                    },
                  },
                ],
              );
            }).catch(e => console.log(e));
          } else if (BUTTONS[buttonIndex] === '采集设备图片（从相册选择）') {
            // console.log('采集设备图片（从相册选择）');
            ImagePicker.openPicker({
              width: 300,
              height: 400,
              cropping: false,
              compressImageQuality: 0.2,
            }).then(image => {
              Alert.alert(
                '提示',
                '是否上传图片',
                [
                  {
                    text: '取消',
                    style: 'cancel',
                  },
                  {
                    text: '确定',
                    onPress: () => {
                      const images = [{ uri: image.path, type: 'multipart/form-data', name: `${new Date().getTime()}.png` }];
                      this.submitImg(images);
                    },
                  },
                ],
              );
            }).catch(e => console.log(e));
          } else if (BUTTONS[buttonIndex] === '故障申报') {
            global.navigation.navigate({
              routeName: 'AddIncident',
              params: {
                flag: 'device',
                sbid: listData.equipmentId,
                sbmc: listData.equipmentName,
                sbbm: listData.equipmentCode,
                equipObjType: listData.objType,
                maintOrgId: listData.maintOrgId,
                maintOrgName: listData.maintOrgName,
              },
            });
          }
        },
      )
    );
  }

  render() {
    const { showLoading, listData, propertyData } = this.state;
    return (
      <View style={styles.container}>
        <View style={styles.headerContainer}>
          <View style={styles.headerTitle}>
            <ZlstIcon
              onPress={this._toMianPage}
              style={styles.backIcon}
              name="fanhui"
              size={20}
              color={fontColor}
            />
            <Text style={styles.headerText}>设备详情</Text>
            <View style={styles.rightOperate}>
              <TouchableOpacity onPress={() => this.addBtn()}>
                <Icon
                  type="MaterialCommunityIcons"
                  name="dots-horizontal"
                  style={{ color: '#ffffff' }}
                />
              </TouchableOpacity>
            </View>
          </View>
          <View style={styles.headerInfo}>
            <View style={styles.imageContent}>
              <Image style={styles.imageCls} source={this._showDetaiImage()} />
            </View>
            <View style={styles.otherSimpleInfo}>
              <View>
                <Text style={styles.colorWhite}>{listData.equipmentName}</Text>
              </View>
              <View>
                <Text style={styles.colorWhite}>设备编号：{listData.equipmentCode}</Text>
              </View>
              <View>
                <Text style={styles.colorWhite}>使用单位：{listData.userOrgDepartment}</Text>
              </View>
            </View>
          </View>
        </View>
        <View style={styles.tabContent}>
          {/* <Tabs locked={true} onChangeTab={this._onChangeTab} tabBarUnderlineStyle={styles.tabBarUnderlineStyle}>
            <Tab heading="设备信息">
              <ScrollView>
                <Tab1 data={this.state.listData} />
              </ScrollView>
            </Tab>
            <Tab heading="资产信息" style={{ backgroundColor: Theme.myPrimary }}>
              <Tab2 data={propertyData} />
            </Tab>
            <Tab heading="检维修记录" style={{ backgroundColor: Theme.myPrimary }}>
                <Tab3 ref="ref1" />
            </Tab>
          </Tabs> */}
          <Tabs page={this.state.defaultPageIndex} onChangeTab={this._onChangeTab} tabBarUnderlineStyle={styles.tabBarUnderlineStyle}>
            <Tab heading="设备信息" style={{ backgroundColor: Theme.myPrimary }}>
              <ScrollView style={{ backgroundColor: Theme.myPrimary }}>
                <Tab1 data={this.state.listData} />
                <Tab2 data={propertyData} />
              </ScrollView>
            </Tab>
            <Tab heading="技术档案" style={{ backgroundColor: Theme.myPrimary }}>
              <ScrollView style={{ backgroundColor: Theme.myPrimary }}>
                <TabDoc data={this.state.listData} />
              </ScrollView>
            </Tab>
            <Tab heading="检维修记录" style={{ backgroundColor: Theme.myPrimary }}>
                <Tab3 ref="ref1" />
            </Tab>
          </Tabs>
        </View>
      </View>
    );
  }
}
const headerHeight = 120;
const deviceWidth = Dimensions.get('window').width;
const fontColor = '#ffffff';
const headerPadding = {
  top: 18,
  right: 18,
  bottom: 0,
  left: 18,
};
const styles = StyleSheet.create({
  tabBarUnderlineStyle: {
    backgroundColor: '#4465e1',
  },
  container: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    flex: 1,
    backgroundColor: Theme.myPrimary,
  },
  headerContainer: {
    paddingLeft: headerPadding.left,
    paddingTop: headerPadding.top,
    paddingRight: headerPadding.right,
    paddingBottom: headerPadding.bottom,
  },
  headerTitle: {
    display: 'flex',
    justifyContent: 'space-between',
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 10,
  },
  backIcon: {
    width: 24,
  },
  headerText: {
    textAlign: 'center',
    color: fontColor,
  },
  headerInfo: {
    width: deviceWidth - (headerPadding.left + headerPadding.right),
    display: 'flex',
    flexDirection: 'row',
    height: headerHeight,
  },
  imageCls: {
    width: 80,
    height: headerHeight - 40,
    borderRadius: 5,
  },
  otherSimpleInfo: {
    flex: 1,
    height: headerHeight - 40,
    paddingLeft: 8,
    color: fontColor,
  },
  colorWhite: {
    color: fontColor,
  },
  tabContent: {
    flex: 1,
    backgroundColor: Theme.myPrimary,
    width: '100%',
  },
});

export default devicesInfo;
